<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\CouponRequest;
use App\Services\Order\Models\Coupon;
use App\Services\Order\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use  Illuminate\Support\Facades\Auth;

class CouponController extends BaseController
{


    protected $businessState;

    public function __construct(BusinessState $businessState)
    {

        $this->businessState = $businessState;
    }
    public function index(Request $request)
    {
        $key = $request->input('key');
        $userId = $request->input('user_id');
        $expiredAt = $request->input('expired_at');
        $createdAt = $request->input('created_at');

        // 排序
        $sort = $request->input('sort', 'id');
        $order = $request->input('order', 'desc');

        $items = Coupon::query()
            ->when($key, function ($query) use ($key) {
                $query->where('code', 'like', '%' . $key . '%');
            })
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->when($expiredAt, function ($query) use ($expiredAt) {
                $query->whereBetween('expired_at', [Carbon::parse($expiredAt[0]), Carbon::parse($expiredAt[1])]);
            })
            ->when($createdAt, function ($query) use ($createdAt) {
                $query->whereBetween('created_at', [Carbon::parse($createdAt[0]), Carbon::parse($createdAt[1])]);
            })
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));

        return $this->successData($items);
    }


    public function claim(Request $request,$id)
    {
        $user = Auth::user();
        $coupon = Coupon::find($id);

        if (!$user->coupons()->where('coupon_id',$id)->exists()) {

            $user->coupons()->attach($id, [
                'claim_at' => now(),
                'start_time' =>$coupon->expired_days? Carbon::now():$coupon->start_time,
                'end_time' => $coupon->expired_days?Carbon::now()->addDays($coupon->expired_at):$coupon->end_time,
            ]);
            $coupon->decrement('claim_count');

           return  $this->success(__('优惠券已经成功领取'));
        } else {

            return  $this->error(__('优惠券您领取过，无需重复再领取'));
        }


    }

    public function store(CouponRequest $request,Coupon $coupon)
    {
        $data = $request->filldata();
        $coupon->fill($data)->save();
        return $this->success(__('插入优惠券成功'));
    }

    public function edit($id)
    {
        $coupon = Coupon::findOrFail($id);

        return $this->successData(compact('coupon'));
    }

    public function update(CouponRequest $request, $id)
    {
        $item = Coupon::findOrFail($id);
        $item->fill($request->filldata())->save();

        return $this->success(__('优惠券更新成功'));
    }

    public function delete(Request $request,$id)
    {
        Coupon::destroy($id);

        return $this->success(__('优惠券删除成功'));
    }

    public function destroy(Request $request)
    {
        $ids=  $request->input('ids',[]);
        if (!$ids){
            return $this->error(__('参数错误'));
        }

        Coupon::destroy($ids);
        return $this->success(__('批量优惠券删除成功'));
    }
    public function checkCode($code)
    {
        $coupon = Coupon::query()->where('code',$code)->first()->toArray();
        $couponRecord = UserCoupon::query()->where('coupon_id',$coupon['id'])->where('user_id',Auth::id())->first();
        $userCoupon =$couponRecord?$couponRecord->toArray():[];
        $canUse = 0;
        if ($this->check()) {
            $canUse = (int)$this->businessState->couponCanUse($this->id(), $coupon,$userCoupon);

        }
     return $this->data(['coupon'=>$coupon,'canUse'=>$canUse]);
    }




}
